<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="110px"
    >
      <el-form-item label="项目名称" prop="projectCode">
        <el-select
          @change="changeCode"
          style="width:100%"
          v-model="dataForm.projectCode"
          placeholder="请选择项目"
        >
          <el-option
            v-for="item in optionsprojectId"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="人员" prop="personnelId">
        <el-select
          style="width:100%"
          v-model="dataForm.personnelId"
          placeholder="请选择人员"
        >
          <el-option
            v-for="item in optionspersonnelName"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同期限类型" prop="contractPeriodType">
        <el-select
          style="width:100%"
          v-model="dataForm.contractPeriodType"
          placeholder="请选择合同期限类型"
        >
          <el-option
            v-for="item in optionsentryExit"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker
          style="width:100%"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          v-model="dataForm.startDate"
          type="datetime"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="到期时间" prop="endDate">
        <el-date-picker
          style="width:100%"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          v-model="dataForm.endDate"
          type="datetime"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="金额(元)" prop="unitPrice">
        <el-input
          v-model="dataForm.unitPrice"
          type="number"
          placeholder="金额(元)"
        ></el-input>
      </el-form-item>
      <el-form-item label="入职时间" prop="entryDate">
        <el-date-picker
          style="width:100%"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          v-model="dataForm.entryDate"
          type="datetime"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传合同图片" prop="attachments">
        <el-upload
          :headers="headers"
          :action="upUrl"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
          :file-list="fileList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      headers: { token: this.$cookie.get("token") },
      upUrl: this.$http.adornUrl(`/sys/getParamenters/changeBase64`),
      optionsprojectId: [],
      optionsentryExit: [],
      optionspersonnelName: [],
      visible: false,
      dataForm: {
        id: 0,
        projectCode: "",
        personnelId: "",
        contractPeriodType: "",
        startDate: "",
        endDate: "",
        unitPrice: "",
        entryDate: "",
        attachments: []
      },
      dataRule: {
        projectCode: [
          { required: true, message: "项目不能为空", trigger: "blur" }
        ],
        personnelId: [
          { required: true, message: "人员不能为空", trigger: "blur" }
        ],
        contractPeriodType: [
          { required: true, message: "合同期限类型不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "到期时间不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "金额(元)不能为空", trigger: "blur" }
        ],
        entryDate: [
          { required: true, message: "入职时间不能为空", trigger: "blur" }
        ],
        attachments: [
          { required: true, message: "合同图片不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.dataForm.attachments = JSON.parse(
        JSON.stringify(fileList).replace(/url/g, "data")
      );
    },
    handlePictureCardPreview(file) {
      console.log(file, "file");
      this.dialogImageUrl = "data:image/png;base64," + file.response.code;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      console.log(this.dataForm.attachments, "jinlai");
      console.log(file);
      if (res.msg === "success") {
        let obj = { name: "", data: "" };
        obj.name = file.name;
        obj.data = file.response.code;
        this.dataForm.attachments.push(obj);
        console.log(this.dataForm.attachments, " this.dataForm.attachments");
      }
    },

    // 选择项目
    changeCode(e) {
      //获取人员
      this.$http({
        url: this.$http.adornUrl(
          `/sys/getParamenters/getPersonnelProfile?projectCode=${e}`
        ),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.optionspersonnelName = data.list;
        }
      });
    },
    // 获取项目
    getCompanyTypes() {
      this.$http({
        url: this.$http.adornUrl(`/sys/getParamenters/getProjectList`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.optionsprojectId = data.list;
        }
      });

      //获取合同期限类型
      this.$http({
        url: this.$http.adornUrl(`/sys/getParamenters/getContractPeriodType`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.optionsentryExit = data.list;
        }
      });
    },
    init(id) {
      this.getCompanyTypes();
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.fileList=[]
        this.dialogImageUrl = "";
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/bemploymentinfo/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.projectCode = data.bEmploymentInfo.projectCode;
              // 回调
              this.changeCode(data.bEmploymentInfo.projectCode)
              this.dataForm.personnelId = data.bEmploymentInfo.personnelId;
              this.dataForm.contractPeriodType =
                data.bEmploymentInfo.contractPeriodType;
              this.dataForm.startDate = data.bEmploymentInfo.startDate;
              this.dataForm.endDate = data.bEmploymentInfo.endDate;
              this.dataForm.unitPrice = data.bEmploymentInfo.unitPrice;
              this.dataForm.entryDate = data.bEmploymentInfo.entryDate;
              this.fileList = JSON.parse(
                data.bEmploymentInfo.attachments.replace(/data/g, "url")
              );
              this.dataForm.attachments = JSON.parse(
                data.bEmploymentInfo.attachments
              );
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        console.log(this.dataForm.attachments, " 提交");
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/bemploymentinfo/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              projectCode: this.dataForm.projectCode,
              personnelId: this.dataForm.personnelId,
              contractPeriodType: this.dataForm.contractPeriodType,
              startDate: this.dataForm.startDate,
              endDate: this.dataForm.endDate,
              unitPrice: this.dataForm.unitPrice,
              entryDate: this.dataForm.entryDate,
              attachments: JSON.stringify(this.dataForm.attachments)
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
